#include"UdpServer.hpp"

void handeler(std::string& msg) 
{
    msg = "server receive: " + msg;
}


void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n" << std::endl;
}

bool SafeCheck(const std::string &cmd)
{
    int safe = false;
    std::vector<std::string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"
    };
    for(auto &word : key_word)
    {
        auto pos = cmd.find(word);
        if(pos != std::string::npos) return false;
    }

    return true;
}

std::string ExcuteCommand(const std::string &cmd)
{
    std::cout << "get a request cmd: " << cmd << std::endl;
    if(!SafeCheck(cmd)) return "Bad man";

    FILE *fp = popen(cmd.c_str(), "r");//popen可以执行一个命令，并返回一个文件指针，指向该命令的输出
    if(nullptr == fp)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while(true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);//命令的执行结果放入这个管道中，可以返回
        if(ok == nullptr) break;
        result += buffer;
    }
    pclose(fp);

    return result;
}

int main(int argc, char* argv[])
{
    if(argc < 2|| argc > 2)
    {
        Usage(argv[0]);
        return 1;
    }
    else
    {
        uint16_t port = stoi(argv[1]);//服务端指定端口值
        UdpServer serv(port);
        serv.Init();
        serv.Run(ExcuteCommand);
    }
    
    return 0;
}